import { useState, useEffect, useCallback } from "react";
import instance from "../pages/utils/https";
import "../css/Position.less";

// 定义 Props 接口
interface PositionProps {
  pId: string | null;
  setPId: React.Dispatch<React.SetStateAction<string | null>>;
  onSearch?: () => void;
}

export default function Position({
  pId,
  setPId,
  onSearch = () => {},
}: PositionProps) {
  const [positions, setPositions] = useState([]);
  const [activePosition, setActivePosition] = useState(pId);

  // 获取职位列表
  const getPosition = async () => {
    try {
      const res = await instance.get("/homePage/getPositionMsg");

      res.data.unshift({jobTitle:"全部",_id:1})

      setPositions(res.data);
    } catch (error) {
      console.error("获取职位信息失败", error);
    }
  };

  // 点击职位
  const handlePositionClick = useCallback(
    (itemId: string) => {
      // 如果点击的是当前选中的职位，则不执行任何操作
      if (activePosition === itemId) return;
      setActivePosition(itemId);
      setPId(itemId); // 调用父组件传入的方法来设置 P_id
      console.log(itemId, "更改P_id");
      onSearch();
    },
    [activePosition, setPId, onSearch]
  );

  useEffect(() => {
    getPosition();
  }, []);

  useEffect(() => {
    // 监听 pId 变化，保持与父组件同步
    if (pId !== activePosition) {
      setActivePosition(pId);
    }
  }, [pId]);

  return (
    <div className="Position">
      {positions.map((item: any, index) => {
        return (
          <p
            key={index}
            className={activePosition === item._id ? "activePosition" : ""}
            onClick={() => handlePositionClick(item._id)}
          >
            {item?.jobTitle}
          </p>
        );
      })}
    </div>
  );
}
